//
//  Utils.m
//  TestPrj
//
//  Created by 朱铅峰 on 2019/12/9.
//  Copyright © 2019 Xing. All rights reserved.
//

#import "Utils.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>

@implementation Utils

- (instancetype)sharedInstance {
    
    return [[self class] sharedInstance];
}

+ (instancetype)sharedInstance {
    
    static dispatch_once_t once;
    static id __singleton__;
    dispatch_once( &once, ^{ __singleton__ = [[self alloc] init]; });
    return __singleton__;
}

#pragma mark 获取文本的高度
+ (CGSize)textSizeOfText:(NSString*)text fontSize:(CGFloat)fontSize width:(CGFloat)width {
    
    return [self textSizeOfText:text font:[UIFont systemFontOfSize:fontSize] width:width];
}

+ (CGSize)textSizeOfText:(NSString *)text font:(UIFont*)font width:(CGFloat)width {
    
    return [self textSizeOfText:text attributes:@{NSFontAttributeName:font} width:width];
}

+ (CGSize)textSizeOfText:(NSString *)text attributes:(NSDictionary *)attributes width:(CGFloat)width {
    
    if ([Utils isEmptyString:text] || !attributes || attributes.count == 0) {
        return CGSizeZero;
    }
    
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    return size;
}

+ (CGSize)textSizeOfAttributedAttr:(NSAttributedString *)attributedString width:(CGFloat)width {
    
    if (!attributedString || ![attributedString isKindOfClass:[NSAttributedString class]] || attributedString.length == 0) {
        return CGSizeZero;
    }
    
    CGSize size = [attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    
    return size;
}

#pragma mark 是否为空字符串
+ (BOOL)isEmptyString:(NSString *)str {
    
    if(str==nil||str==NULL){
        
        return YES;
    }
    
    if ([str isKindOfClass:[NSNull class]]) {
        
        return YES;
    }
    
    if (str.length == 0) {
        
        return YES;
    }
    
    if ([[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        
        return YES;
    }
    
    return NO;
}

#pragma mark trim
+ (NSString *)trimString:(NSString *)str {
    
    if ([self isEmptyString:str]) {
        return nil;
    }
    return [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

#pragma mark 生成imageView
+ (UIImageView *) genImageViewWithFrame:(CGRect)frame {
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    
    return imageView;
}

#pragma mark 创建UILabel
+ (UILabel *)genLabelWithFrame:(CGRect)frame
                     textAlign:(NSInteger)textAlign
                      fontSize:(CGFloat)fontSize
                     textColor:(UIColor *)textColor {
    
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.adjustsFontSizeToFitWidth = YES;
    
    if (textAlign) {
        label.textAlignment = textAlign;
    }
    
    if (fontSize) {
        label.font = [UIFont systemFontOfSize:fontSize];
    }
    
    if (textColor) {
        label.textColor = textColor;
    }
    
    return label;
}

#pragma mark 设置背景颜色圆角等
+ (void) resetView:(UIView*)view
           bgColor:(UIColor*)bgColor
      cornerRadius:(CGFloat)radius
       borderWidth:(CGFloat)bWidth
       borderColor:(UIColor*)bColor {
    
    if (!view || ![view isKindOfClass:[UIView class]]) {
        return;
    }
    
    if (bgColor) {
        view.backgroundColor = bgColor;
    }
    
    if (radius) {
        view.layer.cornerRadius = radius;
    }
    if (bWidth) {
        view.layer.borderWidth = bWidth;
    }
    if (bColor) {
        view.layer.borderColor = bColor.CGColor;
    }
    
    view.layer.masksToBounds = YES;
}

#pragma mark 为textField添加左边距
+ (void)setTextFieldLeftPadding:(UITextField *)textField
                       forWidth:(CGFloat)leftWidth {
    
    CGRect frame = textField.frame;
    frame.size.width = leftWidth;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = leftview;
    UIView *rightView = [[UIView alloc] initWithFrame:frame];
    textField.rightViewMode = UITextFieldViewModeAlways;
    textField.rightView = rightView;
}

#pragma mark 16进制颜色转rgb
+ (UIColor *)colorHexString:(NSString *)hexColor alpha:(float)opacity {
    
    NSString * cString = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor blackColor];
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString * rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString * gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString * bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float)r / 255.0f)
                           green:((float)g / 255.0f)
                            blue:((float)b / 255.0f)
                           alpha:opacity];
}

+ (UIColor *)colorRGB:(NSUInteger)hex alpha:(CGFloat)alpha {
    
    float r, g, b, a;
    a = alpha;
    b = hex & 0x0000FF;
    hex = hex >> 8;
    g = hex & 0x0000FF;
    hex = hex >> 8;
    r = hex;
    
    return [UIColor colorWithRed:r/255.0f
                           green:g/255.0f
                            blue:b/255.0f
                           alpha:a];
}

#pragma mark - 检查网络代理
+ (void)getProxyStatus:(void(^)(BOOL isProxy,NSString *hostName,NSString *portNum,NSString *proxyType))block {

    NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings()); NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));

    NSDictionary *settings = [proxies objectAtIndex:0];

    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
        block(NO,nil,nil,nil);
    }else{
        NSString *hostName = [settings objectForKey:(NSString *)kCFProxyHostNameKey];
        NSString *portNumber = [settings objectForKey:(NSString *)kCFProxyPortNumberKey];
        NSString *type = [settings objectForKey:(NSString *)kCFProxyTypeKey];
        block(YES,hostName,portNumber,type);
    }
}

#pragma mark 警告框
+ (void) showAlertViewWithTitle:(NSString*)title
                        content:(NSString*)content
                    buttonTitle:(NSString *)buttonTitle
                       targetVC:(UIViewController *)targetVC {
    
    [self showAlertViewWithTitle:title
                         content:content
                     buttonTitle:buttonTitle
                     buttonColor:nil
                        targetVC:targetVC];
}
//警告狂
+ (void) showAlertViewWithTitle:(NSString*)title
                        content:(NSString*)content
                    buttonTitle:(NSString *)buttonTitle
                    buttonColor:(UIColor *)buttonColor
                       targetVC:(UIViewController *)targetVC {
    
    if ([Utils isEmptyString:buttonTitle]) {
        buttonTitle = LocalStr(@"Sure");
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:buttonTitle style:UIAlertActionStyleDefault handler:nil];
    [cancelAction setValue:kColorBlack forKey:@"titleTextColor"];
    if (buttonColor) {
        [cancelAction setValue:buttonColor forKey:@"titleTextColor"];
    }
    [alert addAction:cancelAction];
    
    [targetVC presentViewController:alert animated:YES completion:nil];
}

#pragma mark 显示警告框
+ (void) showAlertWithTitle:(NSString*)title
                    content:(NSString*)content
                   targetVC:(UIViewController *)targetVC
               dismissBlock:(void(^)(NSInteger))dismissBlock
               cancelButton:(nonnull NSString *)cancelButton
               otherButtons:(NSArray*)otherButtons {
    
    if ([Utils isEmptyString:cancelButton]) {
        cancelButton = LocalStr(@"Sure");
    }
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    
    if (otherButtons && otherButtons.count>0) {
        NSInteger index = 1;
        for (NSString *sub in otherButtons) {
            UIAlertAction *subAction = [UIAlertAction actionWithTitle:sub style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                dismissBlock(index);
            }];
            [subAction setValue:kColorBlack forKey:@"titleTextColor"];
            [alertVC addAction:subAction];
            index ++;
        }
    }
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButton style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        dismissBlock(0);
    }];
    [cancelAction setValue:kColorBlack forKey:@"titleTextColor"];
    [alertVC addAction:cancelAction];
    
    [targetVC presentViewController:alertVC animated:YES completion:nil];
}

/**
 保存到相册
 
 @param image 图片
 @param targetVC 目标
 @param completeSel 回调SEL,使用UIImageWriteToSavedPhotosAlbum中的SEL- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
 */
+ (void) saveToAlbumWithImage:(nonnull UIImage *)image
                     targetVC:(UIViewController *)targetVC
                  completeSel:(nullable SEL)completeSel {
    
    PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus];
    
    if (author == PHAuthorizationStatusRestricted ||
        author == PHAuthorizationStatusDenied) {
        
        [Utils showAlertWithTitle:LocalStr(@"Unable to access the album")
                          content:LocalStr(@"Open Settings-Privacy-Photos for Setting")
                         targetVC:targetVC
                     dismissBlock:^(NSInteger index) {
                         if (index == 0) {
                             
                             NSDictionary *options = @{UIApplicationOpenURLOptionUniversalLinksOnly : @NO};
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:options completionHandler:^(BOOL success) {
                                 if (success) {
                                     NSLog(@"success");
                                 }
                             }];
                         }
                     } cancelButton:LocalStr(@"To Setting")
                     otherButtons:@[LocalStr(@"Sure")]];
        
        if (targetVC && completeSel) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *name1 = NSStringFromSelector(@selector(image:didFinishSavingWithError:contextInfo:));
                NSString *name2 = NSStringFromSelector(completeSel);
                if ([name1 isEqualToString:name2]) {
                    NSError *error = [[NSError alloc] init];
                    
                    [targetVC performSelector:completeSel withObjects:@[image,error,@{@"info":LocalStr(@"No Permission")}]];
                }
            });
        }
        
    } else if (author == PHAuthorizationStatusAuthorized) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImageWriteToSavedPhotosAlbum(image, targetVC, completeSel, nil);
        });
        
    } else if (author == PHAuthorizationStatusNotDetermined) {
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (status == PHAuthorizationStatusAuthorized) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImageWriteToSavedPhotosAlbum(image, targetVC, completeSel, nil);
                    });
                } else {
                    
                    if (targetVC && completeSel) {
                        NSString *name1 = NSStringFromSelector(@selector(image:didFinishSavingWithError:contextInfo:));
                        NSString *name2 = NSStringFromSelector(completeSel);
                        if ([name1 isEqualToString:name2]) {
                            NSError *error = [[NSError alloc] init];
                            
                            [targetVC performSelector:completeSel withObjects:@[image,error,@{@"info":LocalStr(@"No Permission")}]];
                        }
                    }
                }
            });
        }];
    }
}

//获取截屏
+ (UIImage*)captureImageAtView:(UIView*)view {
    
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
}

//跳转web
+ (void)toWebVCWithUl:(NSString *)ul targetVC:(UIViewController *)vc {
    
    if (@available(iOS 10.0,*)) {
        NSDictionary *options = @{UIApplicationOpenURLOptionUniversalLinksOnly : @NO};
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ul] options:options completionHandler:^(BOOL success) {
            if (success) {
                NSLog(@"success");
            }
        }];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ul]];
    }
}

//base64加解密
+ (NSString *)cBase64EncodeString:(NSString *)string {
    
    NSData *data =[string dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}
+ (NSString *)cBase64DecodeString:(NSString *)string {
    
    NSData *data=[[NSData alloc]initWithBase64EncodedString:string options:0];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}

/**
 获取随机数
 
 @param from 开始l值
 @param to 结束值
 @return 随机数
 */
+ (int) randomNumberFrom:(int)from to:(int)to {
    
    return (int)(from+(arc4random()%(to-from+1)));
}

/**
 数值字符串至少为两位
 
 @param number 数值
 @return 字符串
 */
+ (NSString *)getTwoNumberStr:(NSInteger)number {
    
    if (number < 10) {
        return [NSString stringWithFormat:@"0%d",(int)number];
    } else {
        return [NSString stringWithFormat:@"%d",(int)number];
    }
}

//生成唯一串
+ (NSString *)uniqueString {
    
    NSString *key = @"*@ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefgijklmnopqrst&#";
    NSMutableString *uniqueString = [NSMutableString string];
    for (int i=0; i<20; i++) {
        int index = arc4random_uniform((int)key.length);
        NSString *s = [key substringWithRange:NSMakeRange(index, 1)];
        [uniqueString appendString:s];
    }
    return uniqueString;
}

//获取视频第一帧的截图方法
+ (UIImage *)getVideoPreviewImage:(NSString *)videoURL {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoURL] options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0, 60);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return thumb;
}


#pragma mark - 计算字符串宽高
+ (CGSize)sizeWithFont:(UIFont*)font Str:(NSString*)str withMaxWidth:(CGFloat)maxWidth
{
    NSDictionary *attribute = @{NSFontAttributeName: font};
    CGSize strSize = [str boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)
                                       options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                    attributes:attribute
                                       context:nil].size;
    
    return strSize;
}

+ (CGSize)sizeAttributedWithFont:(UIFont*)font Str:(NSMutableAttributedString*)str withMaxWidth:(CGFloat)maxWidth
{
    CGSize strSize = [str boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) context:nil].size;
    return strSize;
}


+ (NSString *)getImageDataBase64:(UIImage *)image
{
    NSData *imageData =nil;
    
    //图片要压缩的比例，此处100根据需求，自行设置
    CGFloat x =100 / image.size.height;
    if (x >1)
    {
        x = 1.0;
    }
    
    imageData = UIImageJPEGRepresentation(image, x);
    
    return [@"data:image/png;base64," stringByAppendingString:[imageData base64EncodedStringWithOptions:0]];
}

+ (NSMutableAttributedString *)returnStringColor:(NSString *)string rang:(NSRange)rang color:(UIColor *)color
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:string];
    [str addAttribute:NSForegroundColorAttributeName value:color range:rang];
//    [str setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:TextSize(15)],NSForegroundColorAttributeName:BLACK_COLOR} range:NSMakeRange(7, timeString.length-7)];
    return  str;
}

+ (NSMutableAttributedString *)returnStringSize:(NSString *)string rang:(NSRange)rang size:(CGFloat)size
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:string];
    
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:size ] range:rang];
    return  str;
}


@end
